package com.dji.compose_learning.ui.view

import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.dji.compose_learning.ui.theme.Compose_learningTheme


fun Modifier.firstBaselineToTop(firstBaselineToTop: Dp) = this.then(
    layout { measurable, constraints ->
        //测量元素
        val placeable = measurable.measure(constraints)
        //测量之后，获取元素的基线值
        val firstBadeline = placeable[FirstBaseline]
        //元素新的Y坐标 = 新基线坐标 -旧基线坐标
        val placeableY = firstBaselineToTop.roundToPx() - firstBadeline

        val height = placeable.height + placeableY
        layout(placeable.width, height) {
            //设置元素的位置
            placeable.placeRelative(0, placeableY)
        }
    }
)

@Composable
fun CustomViewPage() {
    Compose_learningTheme {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colorScheme.background
        ) {
            Column(modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())) { //这里设置scrollable无法滚动，为什么？
                //sample 1 自定义属性
                TextWithPaddingToBaseline()

                //sample 2 自定义布局-简单顺序布局
                CustomColumn(modifier = Modifier.padding(10.dp)) {
                    Text(text = "this is text line 1")
                    Text(text = "Is this custom column run success")
                    Text(text = "hello, this is buobao here.")
                    Text(text = "here is the last line text")
                }

                //sample 3 自定义布局-实现流式布局
                FlowLayout(modifier = Modifier.padding(10.dp),
                    itemsMargin = 10.dp,
                    lineSpace = 4.dp) {
//                    Chip(text = "hello")
//                    Chip(text = "This is a Tab")
//                    Chip(text = "buobao")
                    Chip(text = "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl" +
                            "xxxxxxxxxxxxxxxxxl")
                    Chip(text = "xxxxxxxxxxxxxxxxxl")
                    Chip(text = "Jack")
                    Chip(text = "Jack")
                    Chip(text = "Jack")
                    Chip(text = "Jack")
                    Chip(text = "Jack")
                    Chip(text = "go home")
                    Chip(text = "go home")
                    Chip(text = "go home")
                    Chip(text = "go home")
                    Chip(text = "go home")
                    Chip(text = "xl")
                    Chip(text = "xl")
                    Chip(text = "88900989789789775968678967896978")
                    Chip(text = "xl")
                    Chip(text = "xxl")
                    Chip(text = "xxl")
                }
                Spacer(modifier = Modifier.height(20.dp))

                //sample 4 自定义布局-实现grid布局
                StaggeredGrid {
                    repeat(50) {
                        Chip(text = "grid$it")
                    }
                }
                //sample5 约束布局
                ConstraintLayoutView()
                //sample6 约束布局2
                ConstraintLayoutView1()
                //sample7 约束布局3
                ConstraintLayoutView2()
            }
        }
    }
}

@Composable
fun TextWithPaddingToBaseline() {
    Text(text = "Hi there!",
        Modifier
            .wrapContentHeight(align = Alignment.Top)
            .wrapContentWidth(align = Alignment.Start)
            .firstBaselineToTop(24.dp)
            .background(Color.Red))
}

/**
 * 自定义垂直布局
 */
@Composable
fun CustomColumn(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
    Layout(content = content, modifier = modifier) { measureables, constraints ->
        val placeables = measureables.map {
            it.measure(constraints)
        }
        var maxWidth = 0
        var maxHeight = 0
        placeables.forEach {
            if (it.width > maxWidth) {
                maxWidth = it.width
            }
            maxHeight += it.height
        }

        var yPosition = 0
        layout(maxWidth, maxHeight) {
            placeables.forEach { placeable ->          //遍历子元素
                placeable.placeRelative(0, yPosition) //设置子元素的位置
                yPosition += placeable.height           //顺序向下摆放
            }
        }
    }
}


/**
 * 自定义流式布局
 */
@Composable
fun FlowLayout(
    modifier: Modifier = Modifier,
    itemsMargin: Dp,
    lineSpace: Dp,
    content: @Composable () -> Unit,
) {
    Layout(modifier = modifier, content = content) { measureables, constainers ->
        val maxWidth = constainers.maxWidth

        var currentWithUsed = 0
        var currentHeightUsed = 0
        var lineMaxHeight = mutableListOf(0)
        var lineIndex = 0
        val placeables = measureables.map {
            val placeable = it.measure(constainers)

            //确定当前item要不要放在这一行
            if ((placeable.width + itemsMargin.roundToPx()) + currentWithUsed > maxWidth) { //不放在当前行
                currentWithUsed = 0
                currentHeightUsed += lineMaxHeight[lineIndex]
                lineIndex++
                lineMaxHeight.add(0)
            }
            currentWithUsed += placeable.width + itemsMargin.roundToPx()
            lineMaxHeight[lineIndex] =
                lineMaxHeight[lineIndex].coerceAtLeast(placeable.height + lineSpace.roundToPx())  //取当前行中高度最大的item为行高
            placeable
        }

        val maxHeight = lineMaxHeight.fold(0) { acc, i -> acc + i }
        currentWithUsed = 0
        currentHeightUsed = 0
        lineIndex = 0
        layout(maxWidth, maxHeight) {
            placeables.forEach {
                if ((it.width + itemsMargin.roundToPx()) + currentWithUsed > maxWidth) {
                    currentWithUsed = 0
                    currentHeightUsed += lineMaxHeight[lineIndex]
                    lineIndex++
                }
                it.placeRelative(currentWithUsed, currentHeightUsed)
                currentWithUsed += it.width + itemsMargin.roundToPx()

            }
        }
    }
}

/**
 * 指定行数grid布局
 */
@Composable
fun StaggeredGrid(modifier: Modifier = Modifier, lines: Int = 3, content: @Composable () -> Unit) {
    Row(modifier = modifier
        .background(color = Color.LightGray)
        .horizontalScroll(rememberScrollState())) {  //添加横向滚动
        Layout(content = content, modifier = Modifier) { measureables, constainers ->
            val rowWidths = IntArray(lines) { 0 }
            val rowHeights = IntArray(lines) { 0 }
            var totalWidth = 0
            var totalHeight = 0

            val placeables = measureables.mapIndexed { index, measurable ->
                val placeable = measurable.measure(constainers)
                val row = index % lines
                rowWidths[row] += placeable.width
                rowHeights[row] = rowHeights[row].coerceAtLeast(placeable.height)
                placeable
            }

            for (i in 0 until lines) {
                totalWidth = totalWidth.coerceAtLeast(rowWidths[i])
                totalHeight += rowHeights[i]
            }

            layout(totalWidth, totalHeight) {
                val widthUsed = IntArray(lines) { 0 }
                var heightUsed = 0

                placeables.forEachIndexed { index, placeable ->
                    val row = index % lines
                    placeable.placeRelative(widthUsed[row], heightUsed)
                    widthUsed[row] += placeable.width
                    if (row == lines - 1) {
                        heightUsed = 0
                    } else {
                        heightUsed += placeable.height
                    }
                }
            }
        }
    }
}

/**
 * item布局
 */
@Composable
fun Chip(modifier: Modifier = Modifier, text: String) {
    Surface(modifier = modifier.padding(2.dp),
        color = MaterialTheme.colorScheme.onSecondary,
        shape = RoundedCornerShape(2.dp)) {
        Row(modifier = modifier) {
            Icon(imageVector = Icons.Filled.Star, contentDescription = "")
            Spacer(modifier = Modifier.width(10.dp))
            Text(text = text)
        }
    }
}


/**
 * 约束布局使用
 */
@Composable
fun ConstraintLayoutView() {
    ConstraintLayout(modifier = Modifier
        .padding(10.dp)
        .background(Color.Gray)) {
        val (button, text) = createRefs() //创建约束引用
        Button(onClick = { /*TODO*/ }, modifier = Modifier.constrainAs(button) {
            top.linkTo(parent.top, margin = 16.dp)
        }) {
            Text(text = "Button")
        }

        Text(text = "this is a text", modifier = Modifier.constrainAs(text) {
            top.linkTo(button.bottom, margin = 16.dp)
            centerHorizontallyTo(parent)
        })
    }
}

/**
 * 特别关注barrier的使用
 */
@Composable
fun ConstraintLayoutView1() {
    ConstraintLayout(modifier = Modifier
        .padding(10.dp)
        .background(Color.Gray)) {
        val (button, button2, text) = createRefs() //创建约束引用
        Button(onClick = { /*TODO*/ }, modifier = Modifier.constrainAs(button) {
            top.linkTo(parent.top, margin = 16.dp)
        }) {
            Text(text = "Button 1")
        }

        Text(text = "this is a text", modifier = Modifier.constrainAs(text) {
            top.linkTo(button.bottom, margin = 16.dp)
            centerAround(button.end)  //以button的尾部位置为text的居中位置
        })
        //将button和text组合起来，建立一个屏障(barrier)
        val barrier = createEndBarrier(button, text)
        Button(onClick = { /*TODO*/ }, modifier = Modifier.constrainAs(button2) {
            top.linkTo(parent.top, margin = 16.dp)
            start.linkTo(barrier) //以创建的barrier为起始位置
        }) {
            Text(text = "Button 2")
        }
    }
}

/**
 * guideline的基本使用
 */
@Composable
fun ConstraintLayoutView2() {
    ConstraintLayout(
        modifier = Modifier
            .padding(10.dp)
            .background(Color.Gray)) {
        val text = createRef()
        val guideline = createGuidelineFromStart(0.5f)
        Text(text = "This is a gooooooooooooooooooooooooooooooooooooooood place.",
            modifier = Modifier.constrainAs(text) {
                linkTo(start = guideline, end = parent.end) //屏幕中间位置开始向后放置
                width = Dimension.preferredWrapContent //设置为自动换行
            })
    }
}















